//
//  HMComposePictureView.swift
//  weibo1
//
//  Created by 代亚洲 on 16/4/27.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD


class HMComposePictureView: UICollectionView {
    
    
    // 选择图片调用的闭包
    var selectedPictureClosure: (()->())?
    
    // 当前 PictureView 显示的图片数据
    lazy var images: [UIImage] = []

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置ui
    
    private func setupUI(){
        //设置UICollectionView的背景颜色
        backgroundColor = UIColor.redColor()
        //注册cell
        registerClass(HMComposePictureViewCell.self, forCellWithReuseIdentifier: "cell")
         // 设置UICollectionView 的datasource delegate 等于self 不设置不会执行数据源方法 UICollectionView 上没有数据
        dataSource = self
        delegate = self
    }
    
    internal override func layoutSubviews() {
        super.layoutSubviews()
        //间距
        let margin: CGFloat = 5
        //item的宽
        let itemWH = (self.frame.width - 2 * margin)/3
        // 设置layout的itemSize的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        //左右最小间距为5
        layout.minimumInteritemSpacing = margin
        //上下最小间距为5
        layout.minimumLineSpacing = margin
    }
    
    /// 提供给外界添加图片的方法
    ///
    /// - parameter image: <#image description#>
    func addImage(image: UIImage) {
        if images.count < 9 {
            images.append(image)
            reloadData()
        }else{
            SVProgressHUD.showErrorWithStatus("数量已达上限")
        }
    }

}

///数据源方法
extension HMComposePictureView : UICollectionViewDataSource,UICollectionViewDelegate {
    //返回行
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
         self.hidden = images.count == 0
        return images.count + ((images.count == 0 || images.count == 9) ? 0 : 1)
    }
    //返回行内容
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! HMComposePictureViewCell
        
        cell.backgroundColor = RandomColor
        
        if indexPath.item == images.count {
            // 代表是最后一张（加号按钮）
            cell.image = nil
        }else{
            cell.image = images[indexPath.item]
        }
        
        // 设置删除按钮点击要执行的闭包 删除按钮被点击时 删除点击的cell
        cell.deleteButtonClosoure = { [weak self] in
            self?.images.removeAtIndex(indexPath.item)
            //刷新
            self?.reloadData()
        }

        return cell
    }
    
    // 监听cell的点击
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.item == images.count {
            // 代表最后一个cell被点击了
            // 执行闭包
            selectedPictureClosure?()
            print("cell被点击了")
        }
    }
}

class HMComposePictureViewCell: UICollectionViewCell {
    
    // 删除按钮点击要执行的闭包
    var deleteButtonClosoure: (()->())?
    
    var image: UIImage? {
        didSet{
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                // 隐藏删除按钮
                deleteButton.hidden = true
            }else{
                deleteButton.hidden = false
                imageView.image = image
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置ui
    
    private func setupUI(){
        
        addSubview(imageView)
        addSubview(deleteButton)
        
//        约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.trailing.equalTo(contentView)
        }
    }
    /**
     按钮的点击事件
     */
    @objc private func deleteButtonClick(){
        // 去通知外界更新数据
        // 执行一个闭包
        deleteButtonClosoure?()
        
    }
 /// 懒加载 图片
    private lazy var imageView: UIImageView = UIImageView()
    
    private lazy var deleteButton: UIButton = {
        let deleteButton = UIButton()
        //监听按钮的点击事件
        deleteButton.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        //设置默认状态按钮图片
        deleteButton.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return deleteButton
    }()
}


